#include "stm32f10x.h"
#include "mbsp.h"
#include "mSC.h"
#include "led.h"
#include "usart.h"
#include "key.h"

#define USARTx  USART1
#define KEYQUEUELEN     (16)
uint16_t keyqueue[KEYQUEUELEN] = {0};
uint32_t uartlcdid = 0;
uint32_t oled12864id = 0;

void usart_display_init(void)                    
{
    USARTx_Init(USARTx,115200);
}                         
                                                                                           
void usart_display_setXYZ(int x,int y,int z)  
{
    USARTx_SendStr(USARTx,"\033[");                    
    USARTx_SendOneByte(USARTx,y + 1);
    USARTx_SendStr(USARTx,";");
    USARTx_SendOneByte(USARTx,x + 1);
    USARTx_SendStr(USARTx,"H"); 
}

void usart_display_set_conversely(uint8_t conv)
{
    (conv ? USARTx_SendStr(USARTx,"\033[7m") : USARTx_SendStr(USARTx,"\033[0m"));
}

void usart_display_clear(void)
{
    USARTx_SendStr(USARTx,"\033[2J");
}

void usart_display_c(char c)
{
    USARTx_SendOneByte(USARTx,(uint8_t)c);
}

void oled12864_display_init(void)
{
    initial_lcd();
}

void oled12864_display_setXYZ(int x,int y,int z)
{
    lcd_address(y * 2,x * 8);
}

void oled12864_display_set_conversely(uint8_t conv)
{
    set_conversely(conv);
}

void oled12864_display_clear(void)
{
    clear_screen();
}

void oled12864_display_c(char c)
{
    display_GB2312_string(0,0,(unsigned char *)&c);
}

void deviceInitTask(void *p)
{
	do
	{
		ledInit();
		keyInit();
		
        qCreate((void *)keyqueue,16,KEYQUEUELEN);
        displayRegister(&uartlcdid,usart_display_init,usart_display_setXYZ,setConversely,NULL,NULL,usart_display_clear,usart_display_c);
        displayRegister(&oled12864id,oled12864_display_init,oled12864_display_setXYZ,oled12864_display_set_conversely,NULL,NULL,oled12864_display_clear,oled12864_display_c);
        displaySelect(uartlcdid);
        displayClear();
        displaySelect(oled12864id);
        displayClear();
        displaySelect(uartlcdid);

		display("\033[%d;%dHsystem boot\r\n",10,10);
		
		mscDeleteTask(deviceInitTask);
	}while(0);
}

void ledTask(void *p)
{
    uint32_t temp = 0;
    qOutItem((void *)keyqueue,(uint32_t *)&temp);
    display("\033[%d;%dHkey val: %d\r\n",10,12,temp);
    if(temp & 0x03)
    {
    
    }
}

void keyTask(void *p)
{
    uint16_t keyval;
    qAddItem((void *)keyqueue,keyval);
}

int main(void)
{
	mbspInit();
	mscInit();
	
	//创建任务并初始化传入参数
	mscCreateTask(MSC_TASK_ZERODELAY,0,0,NULL,deviceInitTask);
	mscCreateTask(MSC_TASK_MSDELAY,0,500,NULL,ledTask);
	mscCreateTask(MSC_TASK_MSDELAY,0,100,NULL,keyTask);
	
	mscStart();
	
	while (1);
}	
	

